﻿#include "Id.h"
//#include "XyNet/Common/Logger.h"
#include "XyNet/Common/StringConverter.h"
#include <boost/uuid/uuid_generators.hpp>
#include <boost/uuid/uuid_io.hpp>

namespace XyNet
{
	IdGenerator::IdGenerator()
	{
		reset();
	}

	void IdGenerator::reset()
	{
		*_idCountObject.createUniqueLock()->getObject() = 0;
	}

	Id IdGenerator::operator()()
	{
		auto lock = _idCountObject.createUniqueLock();
		auto& idCount = *lock->getObject();
		++idCount;
		if (idCount <= 0)
		{
			//Logger::getDefault()->logWarning("Id overflow.");
			//throw XYNET_EXCEPTION("ID Overflow.");
			idCount = 1;	// 重设id为1，因为0是空id
		}
		return idCount;
	}

	//////////////////////////////////////////////////////////////////////////

	Uuid::Uuid() : _uuid(boost::uuids::nil_uuid()) {}

	Uuid::Uuid(const string& bytesOrString)
	{
		if (bytesOrString.size() == boost::uuids::uuid::static_size())	// 字节串
		{
			memcpy(_uuid.data, bytesOrString.data(), bytesOrString.size());
		}
		else	// 字符串
		{
			static boost::uuids::string_generator _stringGenerator;
			_uuid = _stringGenerator(bytesOrString);
		}
#ifdef _DEBUG
		_uuidString = toString();
#endif
	}

	Uuid::Uuid(const boost::uuids::uuid& uuid) : _uuid(uuid)
	{
#ifdef _DEBUG
		_uuidString = toString();
#endif
	}

	Bytes Uuid::toBytes() const
	{
		return Bytes(_uuid.begin(), _uuid.end());
	}

	string Uuid::toString(bool uppercase /*= true*/) const
	{
		return boost::uuids::to_string(_uuid);
	}

	string Uuid::toHex(bool uppercase /*= true*/) const
	{
		return StringConverter::bytesToHexString(
			Bytes(_uuid.begin(), _uuid.end()), uppercase);
	}

	string Uuid::toBase64() const
	{
		return StringConverter::bytesToBase64String(
			Bytes(_uuid.begin(), _uuid.end()));
	}

	Uuid Uuid::makeRandomUuid()
	{
		return boost::uuids::random_generator()();
	}
}